package com.stars.easyms.alarm.factory;

import com.stars.easyms.base.bean.LazyLoadBean;
import com.stars.easyms.base.util.FastJsonUtil;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

/**
 * <p>className: AlarmRestTemplateFactory</p>
 * <p>description: http工厂类</p>
 *
 * @author caotieshuan
 * @version 1.5.0
 * @date 2019-12-24 15:37
 */
public class AlarmRestTemplateFactory {

    private static final LazyLoadBean<RestTemplate> REST_TEMPLATE_LAZY_LOAD_BEAN = new LazyLoadBean<>(() -> {
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        restTemplate.setMessageConverters(Collections.singletonList(FastJsonUtil.getFastJsonHttpMessageConverter()));
        return restTemplate;
    });

    public static RestTemplate getRestTemplate() {
        return REST_TEMPLATE_LAZY_LOAD_BEAN.getNonNullBean();
    }

    private static ClientHttpRequestFactory clientHttpRequestFactory() {
        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
        // 整个连接池的并发
        poolingHttpClientConnectionManager.setMaxTotal(1000);
        // 每个主机的并发
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(1000);
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
        // 重启策略
        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
        // 设置超时时间，毫秒
        clientHttpRequestFactory.setConnectTimeout(5000);
        clientHttpRequestFactory.setReadTimeout(5000);
        clientHttpRequestFactory.setConnectionRequestTimeout(5000);
        return clientHttpRequestFactory;
    }

    private AlarmRestTemplateFactory() {
    }
}
